//
//  LVImageView.swift
//  LVWeibo
//
//  Created by lv on 15/7/6.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit
import FFAutoLayout

class LVImageView: UIImageView {
    
    /// 图片下载进度
    var progress: CGFloat = 0 {
        didSet {
            progressView.hidden = (progress == 0)
            progressView.progress = progress
        }
    }
    // 懒加载绘图View
    private lazy var progressView: ProgressView = {
        let pv = ProgressView()
        self.addSubview(pv)
        pv.ff_Fill(self)
        return pv
    }()
    
    /// 进度View 类嵌套只能被iconView使用
    class ProgressView: UIView {
        
        var progress:CGFloat = 0 {
            didSet {
                setNeedsDisplay()
            }
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            backgroundColor = UIColor.clearColor()
        }
        
        required init(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        override func drawRect(rect: CGRect) {
            
            // 画圆
            let r = min(rect.width, rect.height) * 0.4
            let center = CGPoint(x: rect.width * 0.5, y: rect.height * 0.5)
            let ovalRect = CGRect(x:center.x - r , y: center.y - r, width: 2 * r, height: 2 * r)
            let path = UIBezierPath(ovalInRect: ovalRect)
            UIColor(white: 1.0, alpha: 0.5).setFill()
            path.fill()
            
            // 画线
            let start = CGFloat(-M_PI_2)
            let end = progress * CGFloat(2 * M_PI) + start
            let path1 = UIBezierPath(arcCenter: center, radius: r, startAngle: start, endAngle: end, clockwise: true)
            
            path1.addLineToPoint(center)
            path1.closePath()
            UIColor(white: 1.0, alpha: 0.5).setFill()
            path1.fill()
        }
    }
}
